using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Dynamic;
using YTS.Tools;

namespace Test.ConsoleProgram.Algorithm.Solution
{
    [TestDescription("算法: 0014. 最长公共前缀")]
    public class No0014_LongestCommonPrefix : AbsBaseTestItem
    {
        public override void OnTest()
        {
            Assert.TestExe(LongestCommonPrefix, new string[] { "flower", "flow", "flight" }, "fl");
            Assert.TestExe(LongestCommonPrefix, new string[] { "dog", "racecar", "car" }, "");

            Assert.TestExe(LongestCommonPrefix2, new string[] { "flower", "flow", "flight" }, "fl");
            Assert.TestExe(LongestCommonPrefix2, new string[] { "dog", "racecar", "car" }, "");
        }

        public string LongestCommonPrefix(string[] strs)
        {
            if (strs == null || strs.Length <= 0)
            {
                return "";
            }
            if (strs.Length == 1)
            {
                return strs[0];
            }
            char[] result = strs[0].ToCharArray();
            for (int i = 1; i < strs.Length; i++)
            {
                string item = strs[i];
                char[] chars = item.ToCharArray();
                result = Calc(result, chars);
            }
            string value = new string(result);
            return value;
        }
        private char[] Calc(char[] cs1, char[] cs2)
        {
            int minlen = cs1.Length <= cs2.Length ? cs1.Length : cs2.Length;
            List<char> result = new List<char>();
            for (int i = 0; i < minlen; i++)
            {
                if (cs1[i] == cs2[i])
                {
                    result.Add(cs1[i]);
                }
                else
                {
                    break;
                }
            }
            return result.ToArray();
        }

        public string LongestCommonPrefix2(string[] strs)
        {
            if (strs == null || strs.Length <= 0)
            {
                return string.Empty;
            }
            string firstStr = strs[0];
            if (strs.Length == 1)
            {
                return firstStr;
            }
            int itemLen = firstStr.Length;
            int sumCount = strs.Length;
            for (int i = 0; i < itemLen; i++)
            {
                var c = firstStr[i];
                for (int j = 1; j < sumCount; j++)
                {
                    if (i == strs[j].Length || c != strs[j][i])
                    {
                        return firstStr.Substring(0, i);
                    }
                }
            }
            return firstStr;
        }
    }
}
